package main

import (
	"gitee.com/stlswm/ConfigAdapter/JsonConfig"
	_ "github.com/CodyGuo/godaemon"
	"github.com/kardianos/service"
	"go_com_to_ws/com"
	"go_com_to_ws/ws"
	"log"
	"os"
	"path/filepath"
	"time"
)

var logger service.Logger

type program struct{}

func (p *program) Start(s service.Service) error {
	// Start should not block. Do the actual work async.
	go p.run()
	return nil
}
func (p *program) run() {
	// Do work here
	// 当前目录
	var dir string
	var err error
	if len(os.Args) >= 2 && os.Args[1] != "" {
		dir = os.Args[1]
	} else {
		dir, err = filepath.Abs(filepath.Dir(os.Args[0]))
		log.Println(os.Args)
		if err != nil {
			panic(err)
		}
	}
	log.Printf("配置文件加载目录：%s", dir)
	// 配置解析
	var config struct {
		WebSocketPort string
		PortName      string
	}
	err = JsonConfig.Load(dir+"/config.json", &config)
	if err != nil {
		panic(err)
	}
	go ws.Start(config.WebSocketPort) //启动websocket服务
	com.Listen(config.PortName)
}

func (p *program) Stop(s service.Service) error {
	// Stop should not block. Return with a few seconds.
	return nil
}

func sleep() {
	time.Sleep(time.Second * 5)
}

func main() {
	svcConfig := &service.Config{
		Name:        "go_com_to_ws",
		DisplayName: "go_com_to_ws",
		Description: "go_com_to_ws",
	}
	prg := &program{}
	s, err := service.New(prg, svcConfig)
	if err != nil {
		log.Fatal(err)
	}
	logger, err = s.Logger(nil)
	if err != nil {
		log.Fatal(err)
	}
	err = s.Run()
	if err != nil {
		logger.Error(err)
	}
}
